from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.db.models import Count, Avg, Sum
from tickets.models import Ticket
from assets.models import Asset
from django.utils import timezone
from datetime import timedelta

@login_required
def report_dashboard(request):
    """报表统计仪表板"""
    # 获取最近30天的数据
    thirty_days_ago = timezone.now() - timedelta(days=30)
    
    # 工单统计
    ticket_stats = {
        'total': Ticket.objects.count(),
        'pending': Ticket.objects.filter(status='pending').count(),
        'in_progress': Ticket.objects.filter(status='in_progress').count(),
        'completed': Ticket.objects.filter(status='completed').count(),
        'closed': Ticket.objects.filter(status='closed').count(),
        'recent': Ticket.objects.filter(created_at__gte=thirty_days_ago).count(),
    }
    
    # 设备统计
    asset_stats = {
        'total': Asset.objects.count(),
        'active': Asset.objects.filter(status='active').count(),
        'maintenance': Asset.objects.filter(status='maintenance').count(),
        'retired': Asset.objects.filter(status='retired').count(),
    }
    
    # 优先级统计
    priority_stats = {
        'high': Ticket.objects.filter(priority='high').count(),
        'medium': Ticket.objects.filter(priority='medium').count(),
        'low': Ticket.objects.filter(priority='low').count(),
    }
    
    context = {
        'ticket_stats': ticket_stats,
        'asset_stats': asset_stats,
        'priority_stats': priority_stats,
        'thirty_days_ago': thirty_days_ago,
    }
    
    return render(request, 'reports/dashboard.html', context)
